package com.allen.imsystem.user.service.impl;

import com.allen.imsystem.common.exception.BusinessException;
import com.allen.imsystem.common.exception.ExceptionType;
import com.allen.imsystem.user.model.dto.EmailMessage;
import com.allen.imsystem.user.service.MailService;
import freemarker.core.ParseException;
import freemarker.template.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @ClassName MailService
 * @Description
 * @Date 2022/4/11
 * @Version 1.0
 */
@Service
public class MailServiceImpl implements MailService, MessageListener {

    @Autowired
    private JavaMailSender javaMailSender;
    // 自动注入FreeMarker配置类,用户获取模板
    @Autowired
    private Configuration configuration;
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${mail.smtp.username}")
    private String FROM;
    @Value("${mail.smtp.defaultEncoding}")
    private String ENCODING;


    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer<EmailMessage> serializer = (RedisSerializer<EmailMessage>) redisTemplate.getValueSerializer();
        EmailMessage emailMessage = serializer.deserialize(message.getBody());
        boolean success = this.sendMailFreeMarker(emailMessage.getSubject(), emailMessage.getFileLocation(),
                                                  emailMessage.getEmailAddress(), emailMessage.getModel());
        if(!success){
            throw new BusinessException(ExceptionType.SERVER_ERROR, "发送邮件失败");
        }
    }

    @Override
    public boolean sendMailFreeMarker(String subject, String location, String emailAddress, Map<String,String> model) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(mimeMessage,true,ENCODING);
            helper.setFrom(FROM);       // 发送方
            helper.setTo(emailAddress); // 接收方
            helper.setSubject(subject); // 主题

            //设置文本内容
            Template template = configuration.getTemplate("mail.ftl");
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

            helper.setText(content,true);
            //设置附件
            if(location != null){
                File file = FileUtils.getFile(location);
                FileSystemResource resource = new FileSystemResource(file);
                helper.addAttachment(file.getName(),resource);
            }
            //发送
            javaMailSender.send(mimeMessage);

        }catch (MessagingException e){
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (TemplateNotFoundException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (MalformedTemplateNameException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }


}